from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
import os

from config.setting_logging import setting_logging

app = Flask(__name__, instance_path=os.path.abspath(os.path.join(os.getcwd(), "../app")))


def make_setting():
    from framework.constant.SysConstant import SysConstant
    from config.setting_prod import SettingProd
    from config.setting_test import SettingTest
    from config.setting_dev import SettingDev
    from config.setting_globle import SettingGloble
    config = {
        'dev': SettingDev,
        'prod': SettingProd,
        'test': SettingTest,
    }
    envValue = os.environ.get('APP_ENV')
    if envValue is None:
        envValue = SettingGloble.APP_ENV
    app.config.from_object(config[envValue])
    print('当前环境值', app.config["ENVNAME"])
    tmp_path = SysConstant.tmp_path
    if not os.path.exists(tmp_path):
        os.makedirs(tmp_path)

    logs_path = SysConstant.logs_path
    if not os.path.exists(logs_path):
        os.makedirs(logs_path)

    setting_logging(app, logs_path, envValue)

    # old setting
    # from config import setting_dev
    # from config import setting_prod
    # from config import setting_job
    # from config import setting_test
    # #TODO 需通过os.urandom(24)重新生成一个唯一key
    # app.secret_key = b'\xff\xec\xc9Qn\x07d\xee\x1e M\xb7^\xf1\x03S'
    #
    # if 'job' in sys.argv[0]:
    #     app.config.from_object(setting_job)
    # elif '/data/deploy/prod' in sys.path[0]:
    #     app.config.from_object(setting_prod)
    # elif '/data/deploy/test' in sys.path[0]:
    #     app.config.from_object(setting_test)
    # else:
    #     app.config.from_object(setting_dev)
    #


make_setting()
db = SQLAlchemy(app)
CORS(app, supports_credentials=True)


def init_app():
    from app import blueprint
    blueprint.register(app)
    from framework.context import request_context_handlers


init_app()

if (app.config.get("KAFKA_SWITCH")  == True):
    import mq
